package org.fig.dependency.lookup;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description: 演示 NoUniqueBeanDefinitionException
 * @Author: Flynn Vanderboom
 * @Data: 2021/6/18 14:16
 */
@Configuration
public class NoUniqueBeanDefinitionExceptionDemo {
    public static void main(String[] args) {
        //创建BeanFactory容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        //将当前类  NoUniqueBeanDefinitionExceptionDemo 作为配置类 (Configuration Class)
        applicationContext.register(NoUniqueBeanDefinitionExceptionDemo.class);

        //启动应用上下文
        applicationContext.refresh();


        try {
            //抛出异常
            applicationContext.getBean(String.class);
            //applicationContext.getBeansOfType(String.class);
        } catch (NoUniqueBeanDefinitionException exception) {
            System.err.printf("Spring 上下文存在 %d 个 %s 类型的Bean。具体原因 %s",
                    exception.getNumberOfBeansFound(), String.class.getName(), exception.getMessage());
        }


        //关闭上下文
        applicationContext.close();
    }

    @Bean(value = "primary")
    public String bean1() {
        return "Hello World";
    }


    @Bean
    public String bean2() {
        return "Hello World";
    }

    @Bean
    public String bean3() {
        return "Hello World";
    }
}
